#!/bin/bash

# 日志查看脚本

echo "=== 企洺星官网日志查看工具 ==="
echo ""

# 检查日志目录是否存在
if [ ! -d "logs/nginx" ]; then
    echo "创建日志目录..."
    mkdir -p logs/nginx
fi

# 显示菜单
show_menu() {
    echo "请选择要查看的日志："
    echo "1. 查看Nginx访问日志"
    echo "2. 查看Nginx错误日志"
    echo "3. 查看后端管理API访问日志"
    echo "4. 实时监控访问日志"
    echo "5. 实时监控错误日志"
    echo "6. 查看所有日志文件"
    echo "7. 清理日志文件"
    echo "0. 退出"
    echo ""
}

# 查看访问日志
view_access_log() {
    echo "=== Nginx访问日志 ==="
    if [ -f "logs/nginx/access.log" ]; then
        tail -50 logs/nginx/access.log
    else
        echo "访问日志文件不存在"
    fi
}

# 查看错误日志
view_error_log() {
    echo "=== Nginx错误日志 ==="
    if [ -f "logs/nginx/error.log" ]; then
        tail -50 logs/nginx/error.log
    else
        echo "错误日志文件不存在"
    fi
}

# 查看API访问日志
view_admin_log() {
    echo "=== 后端管理API访问日志 ==="
    if [ -f "logs/nginx/admin_access.log" ]; then
        tail -50 logs/nginx/admin_access.log
    else
        echo "API访问日志文件不存在"
    fi
}

# 实时监控访问日志
monitor_access_log() {
    echo "=== 实时监控访问日志 (按Ctrl+C退出) ==="
    if [ -f "logs/nginx/access.log" ]; then
        tail -f logs/nginx/access.log
    else
        echo "访问日志文件不存在"
    fi
}

# 实时监控错误日志
monitor_error_log() {
    echo "=== 实时监控错误日志 (按Ctrl+C退出) ==="
    if [ -f "logs/nginx/error.log" ]; then
        tail -f logs/nginx/error.log
    else
        echo "错误日志文件不存在"
    fi
}

# 查看所有日志文件
view_all_logs() {
    echo "=== 所有日志文件 ==="
    ls -la logs/nginx/
    echo ""
    echo "文件大小："
    du -h logs/nginx/*
}

# 清理日志文件
clean_logs() {
    echo "=== 清理日志文件 ==="
    read -p "确定要清理所有日志文件吗？(y/N): " confirm
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        > logs/nginx/access.log
        > logs/nginx/error.log
        > logs/nginx/admin_access.log
        echo "日志文件已清理"
    else
        echo "取消清理"
    fi
}

# 主循环
while true; do
    show_menu
    read -p "请输入选项 (0-7): " choice
    
    case $choice in
        1)
            view_access_log
            ;;
        2)
            view_error_log
            ;;
        3)
            view_admin_log
            ;;
        4)
            monitor_access_log
            ;;
        5)
            monitor_error_log
            ;;
        6)
            view_all_logs
            ;;
        7)
            clean_logs
            ;;
        0)
            echo "退出日志查看工具"
            exit 0
            ;;
        *)
            echo "无效选项，请重新选择"
            ;;
    esac
    
    echo ""
    read -p "按回车键继续..."
    clear
done
